
package com.filetransfer.client.message.defaultadapter;

import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;

import com.filetransfer.client.message.SendMessageCallBack;
import com.filetransfer.transport.command.FileInfoMessage;
import com.filetransfer.transport.util.XStreamWireFormat;
import com.filetransfer.util.LogUtil;


/**
 * 功能说明:  发送消息Runnable类<br>
 * 开发人员: hanxuetong <br>
 * 开发时间: 2014-7-28 <br>
 * ======== ====== ============================================ <br>
 * 
 */
public class SendMessageHandle implements Runnable{

	private Socket socket = null;
	private FileInfoMessage fileInfoMessage;
	private SendMessageCallBack sendMessageCallBack;

	public SendMessageHandle( FileInfoMessage fileInfoMessage)
	{
		this.fileInfoMessage=fileInfoMessage;	

	}
	
	public SendMessageHandle( FileInfoMessage fileInfoMessage,SendMessageCallBack sendMessageCallBack)
	{
		this.fileInfoMessage=fileInfoMessage;	
		this.sendMessageCallBack=sendMessageCallBack;
	}
	
	public void run() {

		 if(createConnection()){ 
			 
			  DataOutputStream dos=null;
			  try {  
                
                   dos = new DataOutputStream(socket.getOutputStream());  
                     
                  // String fileMd5=MD5Util.getMD5(file);
                   
                 /*  dos.writeUTF(fileInfo.getId());
                   dos.writeUTF(fileInfo.getMd5()); 
                   dos.writeInt(fileInfo.getState()); */ 
                   dos.writeUTF(XStreamWireFormat.marshalText(fileInfoMessage));
                   dos.flush();  
                   if(sendMessageCallBack!=null)
                   {
                	   sendMessageCallBack.sucessMessageCallBack(fileInfoMessage);
                   }
                  
               } catch (Exception e) { 
            	   if(sendMessageCallBack!=null)
                   {
                	   sendMessageCallBack.failMessageCallBack(fileInfoMessage);
                   }
                  LogUtil.err(e.getMessage(), e);
               }finally{
               	
              	 try {
               		 if(dos!=null)
               		 {
               			dos.close();
               		 }
					
					} catch (IOException e1) {
						e1.printStackTrace();
					} 
               	 
              
               	
               	try {
						socket.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
               }
			 
		 }
		
		
	}
	
	
    private boolean createConnection() {  
        try {  
        	 socket = new Socket(fileInfoMessage.getSendToIp(),fileInfoMessage.getSendToPort());  
            System.out.println("连接消息服务器成功！");  
            return true;  
        } catch (Exception e) {  
            System.out.println("连接消息服务器失败！");  
            return false;  
        }   
    } 

}
